package com.code.lightning.code.base;

import com.code.lightning.config.BasicDataBaseConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库工具类
 * 使用DBCP连接池
 * @author LGX_TvT
 * @date 2021-01-14 23:48
 */
@Slf4j
public class BasicDBConnect {

    /**
     * 数据源
     */
    private static final BasicDataSource DATA_SOURCE = new BasicDataSource();

    /**
     * 是否初始化配置
     */
    private static boolean IS_INIT_FLAG = false;

    /**
     * 初始化
     * @param config 数据库连接配置
     */
    public static void init(BasicDataBaseConfig config) {
        if (!IS_INIT_FLAG) {
            DATA_SOURCE.setDriverClassName(config.getDriver());
            DATA_SOURCE.setUsername(config.getUser());
            DATA_SOURCE.setPassword(config.getPassword());
            DATA_SOURCE.setUrl(config.getUrl());
            DATA_SOURCE.setInitialSize(config.getInitialSize());
            DATA_SOURCE.setMaxTotal(config.getMaxTotal());
            DATA_SOURCE.setMaxIdle(config.getMaxIdle());
            DATA_SOURCE.setMinIdle(config.getMinIdle());
            DATA_SOURCE.setMaxWaitMillis(config.getMaxWaitMillis());
            IS_INIT_FLAG = true;
            log.info("init BasicDBConnect config success...");
        }
    }

    /**
     * 重置配置
     */
    public static void resetConfig() {
        IS_INIT_FLAG = false;
        log.info("Rest BasicDBConnect Config: IS_INIT_FLAG={}", IS_INIT_FLAG);
    }

    /**
     * 获得连接对象
     */
    public static Connection getConnect() {
        try{
            Connection connection = DATA_SOURCE.getConnection();
            log.info("get Connection success: {}", connection);
            return connection;
        }catch (SQLException e){
            log.error("get Connection Fail: {}", e.getMessage());
        }
        return null;
    }

    public static void close(Connection connection, Statement stmt, ResultSet rs){
        if (rs != null){
            try {
                rs.close();
            }catch (Exception e){
                log.error("close ResultSet Error: {}", e.getMessage());
            }
        }
        if (stmt != null){
            try {
                stmt.close();
            }catch (Exception e){
                log.error("close Statement Error: {}", e.getMessage());
            }
        }
        if (connection != null){
            try {
                connection.close();
            }catch (Exception e){
                log.error("close Connection Error: {}", e.getMessage());
            }
        }
    }
}
